import fs from "then-fs"
//查
async function getData() {
  let str = await fs.readFile('./data.json', 'utf8')
  return JSON.parse(str)
}
// getData().then(res => {
//   console.log(res);
// })

//增
async function addData(obj) {
  try {
    let arr = await getData()
    obj.id = arr[arr.length - 1].id + 1
    arr.push(obj)
    fs.writeFile('./data.json', JSON.stringify(arr))
    return '添加成功'
  } catch (e) {
    return '添加失败'
  }
}
// addData({
//   "author": "宁沪",
//   "bookname": "玉女心经",
//   "publisher": "人民出版社"
// }).then(res => {
//   console.log(res);
// })

//删
async function delData(num) {
  try {
    let arr = await getData()
  let newArr=[]
  arr.forEach(ele => {
    if (ele.id !== num) {
      newArr.push(ele)
    }
    fs.writeFile('./data.json', JSON.stringify(newArr))
  });
    return '删除成功'
  } catch (e) {
    return e
  }

}
// delData(6).then(res => {
//   return console.log(res);
// })

//改
async function updateData(obj) {
  try {
    let arr = await getData()
  let index=arr.indexOf(ele=>obj.id==arr.id)
  arr.splice(index, 1, obj)
  fs.writeFile('./data.json', JSON.stringify(arr))
  return '修改成功'
  } catch (e) {
    return '修改失败'
  }
}
// updateData({
//   "author": "牛逼",
//   "bookname": "玉女心经",
//   "publisher": "人民出版社",
//   "id": 5
// }).then(res => {
//   return console.log(res);
// })
